package jdbc;

import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;


public class Transacciones {
       public static void main(String[] args) {
//        String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
//        String url="jdbc:odbc:conexion";
//        String driver = "org.gjt.mm.mysql.Driver";
//        String url="jdbc:mysql://localhost:3306/pruebas";
        String driver = "oracle.jdbc.OracleDriver";
        String url="jdbc:oracle:thin:@localhost:1521:ORCL";
        
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException ex) {
            System.out.println("Driver incorrecto/Driver no en classpath: " + ex);
            return;
        }
        Connection con = null;
        try {
            con = DriverManager.getConnection(url,"scott","tiger");
            
            con.setAutoCommit(false);
            
            int nivel = Connection.TRANSACTION_SERIALIZABLE;
            con.setTransactionIsolation(nivel);
            
/*            Connection.TRANSACTION_NONE;
            Connection.TRANSACTION_READ_UNCOMMITTED;
            Connection.TRANSACTION_READ_COMMITTED;
            Connection.TRANSACTION_REPEATABLE_READ;
            Connection.TRANSACTION_SERIALIZABLE;
*/            
            
            
            String consulta = "INSERT INTO Persona(nombre,fechanaciminento,sueldo) VALUES (?,?,?)";
            PreparedStatement ps = con.prepareStatement(consulta);
            ps.setString(1,"Ana");
            ps.setDate(2, new Date(System.currentTimeMillis()));
            ps.setFloat(3, 123.56f);
            ps.executeUpdate();
            ps.setString(1,"Ana2");
            ps.setDate(2, new Date(System.currentTimeMillis()));
            ps.setFloat(3, 123.00f);
            ps.executeUpdate();
            ps.setString(1,"Ana3");
            ps.setDate(2, new Date(System.currentTimeMillis()));
            ps.setFloat(3, 123.99f);
            ps.executeUpdate();
            
            if(true) throw new Exception("Rechazamos los cambios");
            
            con.commit();
            
            
           // ....
            
            con.commit();

        } catch (Exception ex) {
            System.out.println("ERROR: " + ex);
            ex.printStackTrace();
            try {
                con.rollback();
            } catch (SQLException ex1) {
                Logger.getLogger(Transacciones.class.getName()).log(Level.SEVERE, null, ex1);
            }
        } finally {
            if (con != null) {
                try {
                    con.close();
                } catch (Exception ex) {
                }
            }
        }


    } 
}
